﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using StockUtil;

namespace StockLib.Data
{
    public class KFileLoader
    {
        public virtual List<KData> Load(Stock stock, KType kType)
        {
            return Load(stock, kType, -1);
        }


        public virtual List<KData> Load(Stock stock, KType kType, int count)
        {
            const int PACK_NUM = 500;

            List<KData> kData = new List<KData>();

            FileInfo fileInfo = new FileInfo(StockData.Instance.GetFileName(stock, DataType.K, kType));
            if (!fileInfo.Exists)
                return kData;

            FileStream fileStream = null;
            int packSize = Marshal.SizeOf(typeof(KFilePack));
            byte[] buffer = new byte[packSize * PACK_NUM];
            try
            {
                fileStream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.Read);
                if (count > 0 && packSize * count < fileStream.Length)
                {
                    fileStream.Position = fileStream.Length - packSize * count;
                }

                int byteNumber = 0;
                while ((byteNumber = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    for (int i = 0; i < byteNumber / packSize; i++)
                    {
                        KFilePack pack = (KFilePack)StructHelper.FromBytes(buffer, i * packSize, typeof(KFilePack));
                        KData data = KFilePack.ToInternal(ref pack);
                        kData.Add(data);
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
                throw ex;
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                    fileStream.Dispose();
                }
            }

            return kData;
        }
    }
}
